//
//  LKCircleScrollView.m
//  LKCircleScrollViewDemo
//
//  Created by LIUKUN-PC on 16/7/12.
//  Copyright © 2016年 liukun. All rights reserved.
//

#import "LKCircleScrollView.h"
#import "NSTimer+LKExtension.h"
#import "UIView+LKScreenDisplaying.h"

@interface LKCircleScrollView ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) NSMutableArray<UIView *> *currentViews;
@property (nonatomic, strong) NSMutableDictionary<NSString *, UIView *> *cacheDic;

@property (nonatomic, assign, readonly) NSInteger totalCount;


@end

@implementation LKCircleScrollView

#pragma mark - API

- (void)reloadData {
    [self loadData];
}

#pragma mark - init

- (instancetype)init {
    if (self = [super init]) {
        [self initSubViews];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self initSubViews];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initSubViews];
    }
    return self;
}

- (void)initSubViews {
    self.scrollTimeInterval = 5;
    
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.delegate = self;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    
    self.pageControl = [[UIPageControl alloc] init];
    self.pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    self.pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    self.pageControl.enabled = NO;
    
    [self addSubview:self.scrollView];
    [self addSubview:self.pageControl];

}

#pragma mark - setupFrame

- (void)layoutSubviews {
    self.scrollView.frame = self.bounds;
    
    for (int i = 0; i < self.currentViews.count; i++) {
        self.currentViews[i].frame = CGRectMake(i * self.bounds.size.width, 0, self.bounds.size.width, self.bounds.size.height);
    }
    self.scrollView.contentSize = CGSizeMake(self.bounds.size.width*3, self.bounds.size.height);
    self.scrollView.contentOffset = CGPointMake(self.bounds.size.width, 0);
    
    self.pageControl.frame = CGRectMake(0, self.bounds.size.height - 57, self.bounds.size.width, 37);
    
}

#pragma mark - Getter & Setter

- (void)setIsAutoScroll:(BOOL)isAutoScroll {
    _isAutoScroll = isAutoScroll;
    [self startAutoScroll];
}

- (void)setDataSource:(id<LKCircleScrollViewDataSource>)dataSource {
    _dataSource = dataSource;
    [self reloadData];
}

- (void)setCurrentIndex:(NSInteger)currentIndex {
    _currentIndex = [self resetPageIndex:currentIndex];
    [self loadData];
    if ([self.delegate respondsToSelector:@selector(circleScrollView:currentIndexDidChange:)]) {
        [self.delegate circleScrollView:self currentIndexDidChange:_currentIndex];
    }
}


- (NSMutableArray<UIView *> *)currentViews  {
    if (!_currentViews) {
        _currentViews = [NSMutableArray<UIView *> array];
    }
    return _currentViews;
}

- (NSMutableDictionary<NSString *,UIView *> *)cacheDic {
    if (!_cacheDic) {
        _cacheDic = [NSMutableDictionary<NSString *, UIView *> dictionary];
    }
    return _cacheDic;
}

- (NSInteger)totalCount {
    
    return [self.dataSource numberOfViewsInCircleScrollView:self];
    
}

#pragma mark - AutoScroll

//自动滚动定时器触发
- (void)startAutoScroll {
    if (!self.isAutoScroll) {
        return;
    }
    self.timer = [NSTimer timerWithTimeInterval:self.scrollTimeInterval target:self selector:@selector(scroll) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    [self.timer restartAfterDelay:self.scrollTimeInterval];
}

//自动滚动方法添加
- (void)scroll {
    if (![self isDisplayedInScreen]) {
        [self.timer stop];
        return;
    }
    [self.scrollView setContentOffset:CGPointMake(self.frame.size.width * 2, 0) animated:YES];
}

#pragma mark - load Data

//加载数据
- (void)loadData {
    if (!self.totalCount) {
        return;
    }
    self.pageControl.numberOfPages = self.totalCount;
    self.pageControl.currentPage = self.currentIndex;
    [self showViewsByCurrentPage:self.currentIndex];
    [self layoutSubviews];
}

#pragma mark - Scroll View Delegate
//滚动视图开始拖拽停止定时器
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.timer pause];
}

//拖拽结束的时候重启定时器
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self.timer restartAfterDelay:self.scrollTimeInterval];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self.scrollView setContentOffset:CGPointMake(self.frame.size.width, 0) animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    int x = scrollView.contentOffset.x;
    if (x >= 2 * self.frame.size.width) {
        self.currentIndex += 1;
    }
    
    if (x <= 0) {
        self.currentIndex -= 1;
    }
}

#pragma mark - 显示图片处理
//获取需要展示的三张页面
- (void)showViewsByCurrentPage:(NSInteger)currentPage {
    
    for (UIView *view in [self.scrollView subviews]) {
        [view removeFromSuperview];
    }
    
    NSInteger previousPage = [self resetPageIndex:currentPage - 1];
    NSInteger nextpage = [self resetPageIndex:currentPage + 1];
    
    [self.currentViews removeAllObjects];
    
    UIView *previousView = [self getShowViewByPage:previousPage];
    [self.currentViews addObject:previousView];
    [self.scrollView addSubview:previousView];
    
    UIView *currentView = [self getShowViewByPage:currentPage];
    [self.currentViews addObject:currentView];
    [self.scrollView addSubview:currentView];
    
    UIView *nextView = [self getShowViewByPage:nextpage];
    [self.currentViews addObject:nextView];
    [self.scrollView addSubview:nextView];
}

//根据页数展示需要展示的对象
- (UIView *)getShowViewByPage:(NSInteger)page {
    //必须做判断，不然会缓存同一个视图
    if (self.totalCount < 3) {
        return [self.dataSource circleScrollView:self viewAtIndex:page];
    }
    
    UIView *view;
    
    if ([[self.cacheDic allKeys] containsObject:[NSString stringWithFormat:@"%ld",page]]) {
        view = self.cacheDic[[NSString stringWithFormat:@"%ld",page]];
    }else{
        view = [self.dataSource circleScrollView:self viewAtIndex:page];
        self.cacheDic[[NSString stringWithFormat:@"%ld",page]] = view;
    }
    return view;
}

//处理索引
- (NSInteger)resetPageIndex:(NSInteger)pageIndex {
    if (pageIndex == -1) {
        if (self.totalCount > 0) {
            return self.totalCount - 1;
        }
       return  0;
    }
    if (pageIndex == self.totalCount) {
       return 0;
    }
    return pageIndex;

}


#pragma mark - Actions

// 触摸事件为了处理模糊手动滑动与自动滑动的影响
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.timer pause];
}

//触摸结束
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.timer restartAfterDelay:self.scrollTimeInterval];
    UITouch *touch = [touches anyObject];
    //判断点击属性实现点击
    if (touch.tapCount == 1) {
        if ([self.delegate respondsToSelector:@selector(circleScrollView:didTapViewAtIndex:)]) {
            [self.delegate circleScrollView:self didTapViewAtIndex:self.currentIndex];
        }
    }
}



@end

